package org.ezplatform.component.fileview.web.rest;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ValidationException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.ParseException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.HttpMultipartMode;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.ezplatform.component.attachment.service.AttachmentService;
import org.ezplatform.component.fileview.service.ArteryPaperViewService;
import org.ezplatform.component.fileview.service.FileViewService;
import org.ezplatform.component.fileview.service.FoxitViewService;
import org.ezplatform.component.fileview.service.OpenOfficeViewService;
import org.ezplatform.component.fileview.service.SuwellViewService;
import org.ezplatform.component.fileview.service.WpsViewService;
import org.ezplatform.component.fileview.util.DealServerIpUtil;
import org.ezplatform.component.fileview.util.FileViewCacheUtil;
import org.ezplatform.component.fileview.util.FileviewSecUtils;
import org.ezplatform.core.common.WebUser;
import org.ezplatform.core.web.view.OperationResult;
import org.ezplatform.system.auth.util.AuthUtils;
import org.ezplatform.system.basic.util.ConfSettingUtils;
import org.ezplatform.util.Encodes;
import org.ezplatform.util.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping({ "/api/w/fileview" })
public class FileViewWebApiController {
	private static final Logger LOG = LoggerFactory.getLogger(FileViewWebApiController.class);

	@Autowired
	private FileViewService fileViewService;

	@Autowired
	private OpenOfficeViewService openOfficeViewService;

	@Autowired
	private WpsViewService wpsViewService;

	@Autowired
	private ArteryPaperViewService arteryPaperViewService;

	@Autowired
	private FoxitViewService foxitViewService;

	@Autowired
	private SuwellViewService suwellViewService;

	/**
	 * 转换
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/convert" })
	@ResponseBody
	public String convert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		WebUser user = AuthUtils.getCurrentUser();
		String jwtToken = user.getJwtToken();
		// 获取预览配置的相关配置项
		String corpId = request.getParameter("corpId");
		String allowDownload = request.getParameter("allowDownload");
		String fileId = request.getParameter("input");
		String filePw = request.getParameter("filePw");
		String isAiRead = request.getParameter("isAiRead");
		// 参数检验
		Map<String, Object> mailParams = new HashMap<String, Object>(10);
		mailParams.put("corpId", corpId);
		mailParams.put("allowDownload", allowDownload);
		mailParams.put("fileId", fileId);
		if (!FileviewSecUtils.checkCommParams(mailParams)) {
			throw new ValidationException(FileviewSecUtils.ERROR_PARAM_MSG);
		}

		if (StringUtils.isEmpty(corpId)) {
			corpId = "0";
		}
		String isSysAttView = ConfSettingUtils.getConfSettingValue("sysAttachmentView", corpId);
		if(!"1".equals(isSysAttView)){
			return "{\"result\":-1,\"data\":\"\",\"message\":\"附件预览未开启\",\"type\":0}";
		}
		String mark = "sysFileViewApp";
		String sysView = ConfSettingUtils.getConfSettingValue(mark, "0");
		LOG.debug("ofd预览sysView：" + sysView);
		// sysView = "foxit";

		// 文件来源 值为0时来源系统附件表 值为1时来源网盘
		String fileSourceType = request.getParameter("fileSourceType") == null ? "sys"
				: request.getParameter("fileSourceType");
		LOG.debug("ofd预览fileId：" + fileId);
		if ("yozo".equals(sysView)) {
			String returnStr = fileViewService.fileview(request, fileId, fileSourceType, jwtToken,filePw);
			return returnStr;
		} else if ("openoffice".equals(sysView)) {
			String returnStr = openOfficeViewService.converOpenOffice(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wps".equals(sysView)) {
			String returnStr = wpsViewService.getWpsView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wpsonline".equals(sysView)) {
			String returnStr = wpsViewService.getWpsOnlineView(request, fileId, fileSourceType, jwtToken, corpId);
			return returnStr;
		} else if ("arterypaper".equals(sysView)) {
			String returnStr = arteryPaperViewService.arteryPaperView(request, fileId, fileSourceType, jwtToken,filePw);
			return returnStr;
		} else if ("foxit".equals(sysView)) {
			String returnStr = foxitViewService.foxitView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("suwell".equals(sysView)) {// 数科预览
			String returnStr = suwellViewService.fileView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		}
		return null;
	}

	/**
	 * 转换
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/convert_dobulescreen" })
	@ResponseBody
	public String convert_dobulescreen(HttpServletRequest request, HttpServletResponse response) throws Exception {
		WebUser user = AuthUtils.getCurrentUser();
		String jwtToken = user.getJwtToken();
		// 获取预览配置的相关配置项
		String corpId = request.getParameter("corpId");
		String allowDownload = request.getParameter("allowDownload");
		String fileId = request.getParameter("input");
		String filePw = request.getParameter("filePw");
		String isAiRead = request.getParameter("isAiRead");
		// 参数检验
		Map<String, Object> mailParams = new HashMap<String, Object>(10);
		mailParams.put("corpId", corpId);
		mailParams.put("allowDownload", allowDownload);
		mailParams.put("fileId", fileId);
		if (!FileviewSecUtils.checkCommParams(mailParams)) {
			throw new ValidationException(FileviewSecUtils.ERROR_PARAM_MSG);
		}

		if (StringUtils.isEmpty(corpId)) {
			corpId = "0";
		}
		String isSysAttView = ConfSettingUtils.getConfSettingValue("sysAttachmentView", corpId);
		if(!"1".equals(isSysAttView)){
			return "{\"result\":-1,\"data\":\"\",\"message\":\"附件预览未开启\",\"type\":0}";
		}
		String mark = "sysFileViewApp";
		String sysView = ConfSettingUtils.getConfSettingValue(mark, "0");
		LOG.debug("ofd预览sysView：" + sysView);
		// sysView = "foxit";

		// 文件来源 值为0时来源系统附件表 值为1时来源网盘
		String fileSourceType = request.getParameter("fileSourceType") == null ? "sys"
				: request.getParameter("fileSourceType");
		LOG.debug("ofd预览fileId：" + fileId);
		if ("yozo".equals(sysView)) {
			String returnStr = fileViewService.fileview(request, fileId, fileSourceType, jwtToken,filePw);
			return returnStr;
		} else if ("openoffice".equals(sysView)) {
			String returnStr = openOfficeViewService.converOpenOffice(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wps".equals(sysView)) {
			String returnStr = wpsViewService.getWpsView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wpsonline".equals(sysView)) {
			String returnStr = wpsViewService.getWpsOnlineView(request, fileId, fileSourceType, jwtToken, corpId);
			return returnStr;
		} else if ("arterypaper".equals(sysView)) {
			String returnStr = arteryPaperViewService.arteryPaperView_dobulescreen(request, fileId, fileSourceType,
					jwtToken,filePw,isAiRead);
			return returnStr;
		} else if ("foxit".equals(sysView)) {
			String returnStr = foxitViewService.foxitView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("suwell".equals(sysView)) {// 数科预览
			String returnStr = suwellViewService.fileView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		}
		return null;
	}


	/**
	 * 转换
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/mobileConvert" })
	@ResponseBody
	public String mobileConvert(HttpServletRequest request, HttpServletResponse response) throws Exception {
		WebUser user = AuthUtils.getCurrentUser();
		String jwtToken = user.getJwtToken();
		// 获取预览配的相关配置项
		String corpId = request.getParameter("corpId");
		if (StringUtils.isEmpty(corpId)) {
			corpId = "0";
		}
		String mark = "sysFileViewApp";
		String sysView = ConfSettingUtils.getConfSettingValue(mark, corpId);
		String fileId = request.getParameter("input");
		// 文件来源 值为0时来源系统附件表 值为1时来源网盘
		String fileSourceType = request.getParameter("fileSourceType") == null ? "sys"
				: request.getParameter("fileSourceType");
		String filePw = request.getParameter("filePw");
		if ("yozo".equals(sysView)) {
			String returnStr = fileViewService.fileview(request, fileId, fileSourceType, jwtToken,filePw);
			return returnStr;
		} else if ("openoffice".equals(sysView)) {
			String returnStr = openOfficeViewService.converOpenOffice(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wps".equals(sysView)) {
			String returnStr = wpsViewService.getWpsView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("wpsonline".equals(sysView)) {
			String returnStr = wpsViewService.getWpsOnlineView(request, fileId, fileSourceType, jwtToken, corpId);
			return returnStr;
		} else if ("arterypaper".equals(sysView)) {
			String returnStr = arteryPaperViewService.arteryPaperMobileView(request, fileId, fileSourceType, jwtToken,filePw);
			return returnStr;
		} else if ("foxit".equals(sysView)) {
			String returnStr = foxitViewService.foxitView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		} else if ("suwell".equals(sysView)) {// 数科预览
			String returnStr = suwellViewService.fileView(request, fileId, fileSourceType, jwtToken);
			return returnStr;
		}
		return null;
	}

	/**
	 * 下载文件
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/convertFile" })
	@ResponseBody
	public void convertFile(HttpServletRequest request, HttpServletResponse response) throws Exception {
		String fileId = request.getParameter("input");
		String convertType = request.getParameter("convertType");
		fileViewService.downloadFile(fileId, convertType, response);
	}

	@RequestMapping(value = { "/test" })
	public String test(HttpServletRequest request, HttpServletResponse response) {
		return "components/fileview/test";
	}

	@RequestMapping(value = { "/realPath" })
	public void realPath(HttpServletRequest request, HttpServletResponse response) {
		String inputEncodeUrl = request.getParameter("pathId");
		String decodeUrl = Encodes.decodeBase64String(inputEncodeUrl);
		String decodeUseUrl = decodeUrl.substring(2, decodeUrl.length() - 2);
		decodeUseUrl = DealServerIpUtil.getFileViewWebUrl(request, decodeUseUrl, "", "");
		try {
			response.sendRedirect(decodeUseUrl);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
	}

	/**
	 * 校验附件是否加密文件预览
	 *
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = { "/checkFileIsJm" })
	@ResponseBody
	public OperationResult checkFileIsJm(HttpServletRequest request, HttpServletResponse response) throws Exception {
        OperationResult result = null;
        Map map = new HashMap();
        String type = "1";//1：非加密 2：加密未给密码 3：加密且给的密码不正确 4:加密且给的密码正确
		WebUser user = AuthUtils.getCurrentUser();
		String jwtToken = user.getJwtToken();
		// 获取预览配置的相关配置项
		String corpId = request.getParameter("corpId");
		String allowDownload = request.getParameter("allowDownload");
		String fileId = request.getParameter("input");
		if(StringUtils.isEmpty(fileId)){
			fileId = request.getParameter("id");
		}
        String filePw = request.getParameter("filePw");

		// 参数检验
		Map<String, Object> mailParams = new HashMap<String, Object>(10);
		mailParams.put("corpId", corpId);
		mailParams.put("allowDownload", allowDownload);
		mailParams.put("fileId", fileId);
		if (!FileviewSecUtils.checkCommParams(mailParams)) {
			throw new ValidationException(FileviewSecUtils.ERROR_PARAM_MSG);
		}

		if (StringUtils.isEmpty(corpId)) {
			corpId = "0";
		}
		String isSysAttView = ConfSettingUtils.getConfSettingValue("sysAttachmentView", corpId);
		if(!"1".equals(isSysAttView)){
            map.put("type",type);
            map.put("msg","预览服务未开启,不校验文件是否加密");
		}else{
			String mark = "sysFileViewApp";
			String sysView = ConfSettingUtils.getConfSettingValue(mark, "0");
			map.put("type", type);
			map.put("msg", "正常预览");
			if(StringUtils.isNotEmpty(fileId)){
				// 文件来源 值为0时来源系统附件表 值为1时来源网盘
				String fileSourceType = request.getParameter("fileSourceType") == null ? "sys" : request.getParameter("fileSourceType");
				LOG.debug("ofd预览fileId：" + fileId);
				if ("yozo".equals(sysView)) {
					Map resMap = FileViewCacheUtil.fileJmPwIsTure(fileId,filePw);
					if((boolean)resMap.get("fileIsNoView")){
						map = fileViewService.checkFileIsJm(request, fileId, fileSourceType, jwtToken, filePw);
						FileViewCacheUtil.setFileJmResultMap(fileId, map, filePw);
					}else{
						if((boolean)resMap.get("fileIsJm")){
							if((boolean)resMap.get("pwIsOkNoVal")){
								map = fileViewService.checkFileIsJm(request, fileId, fileSourceType, jwtToken, filePw);
								FileViewCacheUtil.setFileJmResultMap(fileId, map, filePw);
							}else{
								map = (Map) resMap.get("map");
							}
						}
					}
				} else if ("arterypaper".equals(sysView)) {
					Map resMap = FileViewCacheUtil.fileJmPwIsTure(fileId,filePw);
					if((boolean)resMap.get("fileIsNoView")){
						map = arteryPaperViewService.checkFileIsJm(request, fileId, fileSourceType, jwtToken, filePw);
						FileViewCacheUtil.setFileJmResultMap(fileId, map, filePw);
					}else{
						if((boolean)resMap.get("fileIsJm")){
							if((boolean)resMap.get("pwIsOkNoVal")){
								map = arteryPaperViewService.checkFileIsJm(request, fileId, fileSourceType, jwtToken, filePw);
								FileViewCacheUtil.setFileJmResultMap(fileId, map, filePw);
							}else{
								map = (Map) resMap.get("map");
							}
						}
					}
				}
			}
        }

        return OperationResult.success(map);
	}

	public static String sendPost1(String url, String param) {
		PrintWriter out = null;
		BufferedReader in = null;
		String result = "";
		try {
			URL realUrl = new URL(url);

			URLConnection conn = realUrl.openConnection();
			conn.setRequestProperty("Accept-Charset", "UTF-8");

			conn.setRequestProperty("accept", "*/*");
			conn.setRequestProperty("connection", "Keep-Alive");
			conn.setRequestProperty("user-agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");

			conn.setDoOutput(true);
			conn.setDoInput(true);

			out = new PrintWriter(conn.getOutputStream());

			out.print(param);

			out.flush();

			in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
			String line;
			while ((line = in.readLine()) != null) {
				result = result + line;
			}
		} catch (Exception e) {
			LOG.error(e.getMessage(),e);
			try {
				if (out != null) {
					out.close();
				}
				if (in != null) {
					in.close();
				}
			} catch (IOException ex) {
				LOG.error(ex.getMessage(),ex);
			}
		} finally {
			if (out != null) {
				out.close();
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					LOG.error(e.getMessage(),e);
				}
			}
			
		}
		return result;
	}

	/**
	 * 向指定 URL 上传文件POST方法的请求
	 *
	 * @param url      发送请求的 URL
	 * @param filepath 文件路径
	 * @param type     转换类型
	 * @return 所代表远程资源的响应结果, json数据
	 */
	public static String SubmitPost(String url, String filepath, String type) {
		String requestJson = "";
		HttpClient httpclient = new DefaultHttpClient();
		try {

			HttpPost httppost = new HttpPost(url);
			FileBody file = new FileBody(new File(filepath));
			MultipartEntity reqEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE, null,
					Charset.forName("UTF-8"));
			reqEntity.addPart("file", file); // file为请求后台的File upload;属性
			reqEntity.addPart("convertType", new StringBody(type, Charset.forName("UTF-8")));
			httppost.setEntity(reqEntity);
			HttpResponse response = httpclient.execute(httppost);
			int statusCode = response.getStatusLine().getStatusCode();
			if (statusCode == HttpStatus.SC_OK) {
				HttpEntity resEntity = response.getEntity();
				requestJson = EntityUtils.toString(resEntity);
				EntityUtils.consume(resEntity);
			}
		} catch (ParseException e) {
			LOG.error(e.getMessage(),e);
		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		} finally {
			try {
				httpclient.getConnectionManager().shutdown();
			} catch (Exception ignore) {
				LOG.error(ignore.getMessage(),ignore);
			}
		}
		return requestJson;
	}

	public static void main(String[] args) throws UnsupportedEncodingException {
		/*
		 * String url = "http://192.168.0.209:8081/dcs/convert"; Map<String,String>
		 * param = new HashMap<String,String>(); param.put("inputDir", "123.txt");
		 * param.put("convertType", "1"); String convertUrl = sendPost(url,param);
		 * JSONObject urlJson = JSONObject.parseObject(convertUrl); JSONArray a =
		 * (JSONArray) urlJson.get("data"); String inurl = ""; inurl+= a.get(0); String
		 * b = urlConvert1(inurl);
		 * 
		 * 
		 * /*JSONObject urlJson = JSONObject.parseObject(convertUrl); String inHtmlUrl =
		 * ""; for(java.util.Map.Entry<String,Object> entry:urlJson.entrySet()){
		 * if(entry.getKey() == "data"){ inHtmlUrl += entry.getValue(); } } String
		 * encodeUrl = "\""+Encodes.encodeBase64(inHtmlUrl)+"\""; String
		 * encodeConvertUrl = convertUrl.replace(inHtmlUrl,encodeUrl);
		 */

		/*
		 * String url =
		 * "[\"http://192.168.0.209:8081/dcsOutput/2017/11/14/MTcxMTE0MDgwNDkyNTgx.html\"]";
		 * String downurl = urlConvert(url);
		 * 
		 */
		/*
		 * String previewPath = "http://192.168.0.209:8081/dcsOutput/"; String
		 * previewUrl = "2017/11/14/MTcxMTE0MDgwNDkyNTgx.html"; String inHtmlUrl =
		 * "[\""+previewPath+previewUrl+"\"]"; String encodeUrl =
		 * "\""+Encodes.encodeBase64(inHtmlUrl)+"\""; String encodeConvertUrl =
		 * "{\"result\":0,\"data\":"+encodeUrl+",\"message\":\"转换成功\",\"type\":1}";
		 */
		String inputEncodeUrl = "WyJodHRwOi8vMTkyLjE2OC4xMC4yNTQ6ODg4OC9PRkRDb252ZXJ0Ly9jb252ZXJ0L2NvbnZlcnRFeGNlbFVybD90aHJlYWRJZD0yMzcxM2IzMTU4NDQ0NzJkYTQ1MjcxOTFjM2I2YWJkOCZmaWxlTmFtZT1jMjY1OTllODBiOGI0NGIyOTQyODc1ZDdiMDg0NDg1MS54bHN4JmZpbGV1cmw9aHR0cCUzQSUyRiUyRjE5Mi4xNjguMTAuMjU0JTNBODg4OCUyRmZsZXhiYXNlJTJGYXR0YWNobWVudCUyRmRsJTNGZmlkJTNEZmY4MDgxODE3ZWZiYWExYjAxN2Y1MzEyMjQ2ZDMwNzIlMjZjaGtzdW0lM0Q2MzQwOGRkZjUyM2EwOTgxZjY5MDg3M2UyOWI1MTUyMSUyNmhhc2glM0RkYjRjNGFkZjFhODM0ZmM0MGVhZTQ3ZDhjNjcyYzUzNCUyNmlzUmVtb3ZlTUIlM0QxIl0=&token=eyJhbGciOiJIUzUxMiIsInppcCI6IkRFRiJ9.eNqMkLFOwzAQhl8FZa4l27k4STckFoYihu6VY58rQ5pEdkJbECsz3VjZmHirqq_BOQysyIvv_z_ff-eX7GH02TIrGyh4DYJJax2DvNas5sCZElw5AKllrrNFFqeGYOcqTkeU1jbg8oqLErmuBADYEuuaQB9jAls8NDoiG_tH7FjE8ISB3I2ZQsBuXPsdrnzb-rghWihQuVICJMiSKNOH4daSwVPR3ekdUnH5_ry8v51PH-fTF-ltv_Xd-jgka9hbUiaKuTamn7qRtHiMzyQ6H-J4v7er3nrn0d7oMb2QXAomJMv5lVBLKJZzcOowB_9j0T5sZ9Ronpe8RmkK-kZXVAa1kI1V6SIhtfWaBvpbcpHhYfgVgMYA-foDAAD__w.SsDEUHlqTLU8CACL8oLFOhR6WmTxtruPLlQT1ZZqI-QFMQ5SMAtVUypKjN1Fyf1t5tBF3QJesB7co-jXlVacHA";
		String inHtmlUrl = "http://61.190.4.70:56040/flexoffice/mobile/modules/cms/dist/index.html?time=1634089777359&dd_nav_bgcolor=FF5E97F6#/info/details//1";
//		//inputEncodeUrl = "WyJvcGVub2ZmaWNlIl0=";
		String decodeUrl = Encodes.decodeBase64String(inputEncodeUrl);
//		String encodeUrl = Encodes.urlEncode(inHtmlUrl);
////		String decodeUseUrl = decodeUrl.substring(2, decodeUrl.length()-2);
		LOG.info("decodeUseUrl==" + decodeUrl);
		LOG.info("encodeUrl==" + URLEncoder.encode(inHtmlUrl, "UTF-8"));
//		 
		try {
			FileInputStream file = new FileInputStream("D:\\ceshiwejian\\paper\\test1.ofd");
			InputStreamReader reader = new InputStreamReader(file, "utf8");

			BufferedReader buffer = new BufferedReader(reader);
			StringBuffer strbuf = new StringBuffer();
			String readLine;
			while ((readLine = buffer.readLine()) != null) {
				strbuf.append(readLine);
//                LOG.info(readLine);

			}
			LOG.info(strbuf.toString());

		} catch (IOException e) {
			LOG.error(e.getMessage(),e);
		}
		String modelCode = "cms,goa_document,goa";
		LOG.info(modelCode.contains("goa_document")+"");
	}

}
